package com.android.interfata;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.android.menu.MenuAbout;
import com.android.menu.MenuContact;
import com.android.menu.MenuHelp;
import com.android.menu.MenuLegal;

public class Register  extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Set View to register.xml
        setContentView(R.layout.register);
        
        TextView loginScreen = (TextView) findViewById(R.id.link_to_login);
        
        // Listening to Login Screen link
        loginScreen.setOnClickListener(new View.OnClickListener() 
        {
			public void onClick(View arg0) 
			{
				// Switching to Login Screen/closing register screen
				finish();
			}
		});
        
        Button register = (Button) findViewById(R.id.btnRegister);
        register.setOnClickListener(new View.OnClickListener() 
        {
			public void onClick(View arg0) 
			{
				registerData();
			}
		});
        
    }
    
    private void registerData()
    {
    	AlertDialog.Builder dlgAlert  = new AlertDialog.Builder(this);
    	
    	EditText ed_fName = (EditText) findViewById(R.id.reg_firstname);
    	EditText ed_lName = (EditText) findViewById(R.id.reg_lastname);
    	EditText ed_email = (EditText) findViewById(R.id.reg_email);
    	EditText ed_user = (EditText) findViewById(R.id.reg_username);
    	EditText ed_pass = (EditText) findViewById(R.id.reg_password);
    	EditText ed_repass = (EditText) findViewById(R.id.reg_repassword);
    	
    	String fName = ed_fName.getText().toString();
    	String lName = ed_lName.getText().toString();
    	String email = ed_email.getText().toString();
    	String user = ed_user.getText().toString();
    	String pass = ed_pass.getText().toString();
    	String repass = ed_repass.getText().toString();
    	
    	
    	if (fName.equals("") || lName.equals("") || email.equals("") || 
    		user.equals("") || pass.equals("") || repass.equals("")) 
    	{
    		dlgAlert.setMessage("All fields are mandatory!");
	        dlgAlert.setTitle("Warning");
	        dlgAlert.setPositiveButton("OK", null);
	        dlgAlert.setCancelable(true);
	        dlgAlert.create().show();
    	}
    	else if (pass.length() < 6)
    	{
    		dlgAlert.setMessage("Password has less than 6 characters!");
	        dlgAlert.setTitle("Warning");
	        dlgAlert.setPositiveButton("OK", null);
	        dlgAlert.setCancelable(true);
	        dlgAlert.create().show();
    	}
    	else if(!pass.equals(repass))
    	{
    		dlgAlert.setMessage("Passwords do not match!");
	        dlgAlert.setTitle("Warning");
	        dlgAlert.setPositiveButton("OK", null);
	        dlgAlert.setCancelable(true);
	        dlgAlert.create().show();
    	}
    	else
    	{
    		fName = replace(fName, " ", "%20");
    		lName = replace(lName, " ", "%20");
    		email = replace(email, " ", "%20");
    		user = replace(user, " ", "%20");
			pass = replace(pass, " ", "%20");
			repass = replace(repass, " ", "%20");
			try 
			{
				String xml = XMLfunctions.getXML("Register?Username=" + user + "&Parola=" + pass +
						"&Nume=" + lName + "&Prenume=" + fName + "&Email=" + email);				
	    		Log.d("xml", xml);
	    		
	    		Document doc = XMLfunctions.XMLfromString(xml);	    		
		        int numResults = XMLfunctions.numResults(doc, "Mesaj");
		        Log.d("num", numResults + " ");
		        if (numResults == 1) 		// trebuie sa fie un singur raspuns (nu pot fi doi utilizatori cu aceleasi date)
		        {
		        	NodeList nodes = doc.getElementsByTagName("Mesaje");
			        Element e = (Element)nodes.item(0);
			        String succes = XMLfunctions.getValue(e, "Success");
			        String mesaj = XMLfunctions.getValue(e, "Mesaj");
			        
			        if (mesaj.contains("E-mail") && mesaj.contains("exista deja in"))
			        	mesaj = "E-mail was used before!";
			        
			        
			        dlgAlert.setMessage(mesaj);
			        if (succes.equals("false"))
			        {
			        	dlgAlert.setTitle("Error");
			        	dlgAlert.setPositiveButton("OK", null);
			        }
			        else
			        {
			        	dlgAlert.setTitle("Succes");
			        	dlgAlert.setPositiveButton("Ok", new DialogInterface.OnClickListener()
			        	{
				            public void onClick(DialogInterface dialog, int which) 
				            {
				                finish();
				            }
				        });
			        }
			        
			        dlgAlert.setCancelable(true);
			        dlgAlert.create().show();		        	
		        }
			}
			catch (Exception exc)
			{
				Log.e("register", exc.getMessage());
			}
    	}
    }
    
    
    // inlocuiesc spatiile
 	static String replace(String str, String pattern, String replace)
 	{
 		String str1;
 		int i = 0;
 		while (i < str.length())
 		{
 			
 			if ( str.charAt(i) == ' '  && str.charAt(i+1) == ' ')
 			{
 				str1 = str.substring(0, i) + str.substring(i + 2, str.length());
 				str = str1;
 			}
 			else
 				i++;
 		}	
 		
 	    int s = 0;
 	    int e = 0;
 	    StringBuffer result = new StringBuffer();

 	    while ((e = str.indexOf(pattern, s)) >= 0)
 	    {
 	        result.append(str.substring(s, e));
 	        result.append(replace);
 	        s = e+pattern.length();
 	    }
 	    result.append(str.substring(s));
 	    return result.toString();
 	}
 	
 	
	/*     menu      */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) 
    {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
    	Intent intent;
        switch (item.getItemId()) 
        {
            case R.id.menu_about:     
            	intent = new Intent(getApplicationContext(), MenuAbout.class);
				startActivity(intent);
                break;
            case R.id.menu_help:     
            	intent = new Intent(getApplicationContext(), MenuHelp.class);
				startActivity(intent);
                break;
            case R.id.menu_legal: 
            	intent = new Intent(getApplicationContext(), MenuLegal.class);
				startActivity(intent);
            	break;
            case R.id.menu_contact:
            	intent = new Intent(getApplicationContext(), MenuContact.class);
				startActivity(intent);
            	break;
        }
        return true;
    }
	/*     end menu      */
     
}